package com.gitee.sparta.examples.segment;

import com.gitee.sparta.annotation.SpartaListener;
import com.gitee.sparta.api.SpartaTemplate;
import com.gitee.sparta.core.bean.SpartaChannel;
import com.gitee.sparta.examples.TopicConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * @author zyred
 * @since v 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/segment")
public class SegmentListener {

    @SuppressWarnings("all")
    @Autowired private SpartaTemplate<Object> spartaTemplate;

    @SpartaListener(topics = {TopicConstant.SEGMENT_TOPIC})
    public void segmentListener (SegmentEntity segmentEntity, SpartaChannel channel) {
        log.info("[segment entity] 延迟：{} ms", (System.currentTimeMillis() - segmentEntity.getExpire()));
        channel.renewal();
    }

    /**
     *  模拟插入消息
     *  http://localhost:9605/segment/put?scope=1&times=PT1S,PT5S,PT10S,PT20S
     *
     * @param times PT1S,PT5S,PT10S,PT20S
     * @param scope 循环次数
     */
    @GetMapping("/put")
    public void put (String times, int scope) {
        Random random = new Random();

        for (int i = 0; i < scope; i++) {
            int next = random.nextInt(10000);

            SegmentEntity segment = new SegmentEntity();
            segment.setUserId(String.valueOf(next));
            segment.setExpire(System.currentTimeMillis());

            Set<String> hash = new HashSet<>(Arrays.asList(times.split(",")));
            this.spartaTemplate.writeAsync(TopicConstant.SEGMENT_TOPIC, segment, hash);
        }
    }
}
